"""Fix replication foreign keys

Revision ID: 171f5b91c36e
Revises: 29e866803c47
Create Date: 2020-04-13 22:15:14.597949+00:00

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '171f5b91c36e'
down_revision = '29e866803c47'
branch_labels = None
depends_on = None


def create_foreign_key(*args, **kwargs):
    op.execute(f"DELETE FROM {args[1]} WHERE {args[3][0]} NOT IN (SELECT {args[4][0]} FROM {args[2]})")


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    create_foreign_key(None, 'storage_replication_repl_periodic_snapshot_tasks', 'storage_replication', ['replication_id'], ['id'])
    create_foreign_key(None, 'storage_replication_repl_periodic_snapshot_tasks', 'storage_task', ['task_id'], ['id'])
    with op.batch_alter_table('storage_replication_repl_periodic_snapshot_tasks', schema=None) as batch_op:
        batch_op.drop_references('replication_id')
        batch_op.drop_references('task_id')
        batch_op.create_index(batch_op.f('ix_storage_replication_repl_periodic_snapshot_tasks_replication_id'), ['replication_id'], unique=False)
        batch_op.create_index(batch_op.f('ix_storage_replication_repl_periodic_snapshot_tasks_task_id'), ['task_id'], unique=False)
        batch_op.create_foreign_key(batch_op.f('fk_storage_replication_repl_periodic_snapshot_tasks_replication_id_storage_replication'), 'storage_replication', ['replication_id'], ['id'], ondelete='CASCADE')
        batch_op.create_foreign_key(batch_op.f('fk_storage_replication_repl_periodic_snapshot_tasks_task_id_storage_task'), 'storage_task', ['task_id'], ['id'], ondelete='CASCADE')
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('storage_replication_repl_periodic_snapshot_tasks', schema=None) as batch_op:
        batch_op.drop_constraint(batch_op.f('fk_storage_replication_repl_periodic_snapshot_tasks_task_id_storage_task'), type_='foreignkey')
        batch_op.drop_constraint(batch_op.f('fk_storage_replication_repl_periodic_snapshot_tasks_replication_id_storage_replication'), type_='foreignkey')
        batch_op.create_foreign_key(None, 'storage_replication', ['replication_id'], ['id'])
        batch_op.create_foreign_key(None, 'storage_task', ['task_id'], ['id'])
        batch_op.drop_index(batch_op.f('ix_storage_replication_repl_periodic_snapshot_tasks_task_id'))
        batch_op.drop_index(batch_op.f('ix_storage_replication_repl_periodic_snapshot_tasks_replication_id'))
    # ### end Alembic commands ###
